package com.photoeditor.demo.ui.widget.image.compose;

import android.app.Activity;
import android.content.Context;
import android.graphics.drawable.Drawable;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.widget.EditText;

import com.common.base.ComponentContext;
import com.common.base.utils.DeviceUtils;


/**
 * 主要拦截了键盘出现时的返回健  并转给Activity的onKeyup处理
 */
public class CustomizedEditText extends EditText {

    private static final int DELWIDTH = DeviceUtils.dip2px(ComponentContext.getContext(), 36);
    private boolean mEmpty = true;
    private Drawable mDelIcon;

    private boolean mForce = false;

    public CustomizedEditText(Context context, AttributeSet attrs) {
        super(context, attrs);
        mDelIcon = getCompoundDrawables()[2];
        setCompoundDrawables(null, null, null, null);
    }


    public void setDelIcon(Drawable drawable) {
        mDelIcon = drawable;
    }

    public boolean dispatchTouchEvent(MotionEvent event) {
        if (mDelIcon != null) {
            float x = event.getX();
            float r = getWidth() - DELWIDTH;
            if (x > r && !mEmpty) {
                if (event.getAction() == MotionEvent.ACTION_UP) {
                    setText(null);
                }
                return true;
            } else if (x > r) {
                return true;
            }
        }
        return super.dispatchTouchEvent(event);
    }

    public boolean onPreDraw() {
        boolean empty = TextUtils.isEmpty(getText());
        if (empty == mEmpty && !mForce) {
            return super.onPreDraw();
        }

        mForce = false;
        mEmpty = empty;
        if (mEmpty) {
            setCompoundDrawables(null, null, null, null);
        } else {
            setCompoundDrawables(null, null, mDelIcon, null);
        }
        return false;
    }


    /**
     * 拦截掉键盘的处理
     */
    @Override
    public boolean dispatchKeyEventPreIme(KeyEvent event) {
        if (event.getKeyCode() == KeyEvent.KEYCODE_BACK && event.getAction() == KeyEvent.ACTION_UP) {
            ((Activity) getContext()).onKeyUp(KeyEvent.KEYCODE_BACK, event);
            return true;
        }
        return super.dispatchKeyEventPreIme(event);
    }
}
